﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Criterion;

namespace SuperMarketManagement.DAO.NHibernate
{
    public abstract class GenericDAO<T, TId>
    {
        public GenericDAO(ISession session)
        {
            Session = session;
        }

        protected ISession Session { get; set; }

        public virtual T Load(TId id)
        {
            return Session.Load<T>(id);
        }

        public virtual T LoadAndLock(TId id)
        {
            return Session.Load<T>(id, LockMode.Upgrade);
        }


        public virtual IList<T> GetAll()
        {
            return Session.CreateCriteria(typeof(T)).List<T>();
        }

        public virtual IEnumerable<T> GetBlock(int start, int count)
        {
            var criteria = Session.CreateCriteria(typeof(T));
            criteria.SetFirstResult(start).SetMaxResults(count);
            return criteria.List<T>();
        }

        public virtual int Count()
        {
            return Session.CreateCriteria(typeof (T)).SetProjection(Projections.Count("*")).UniqueResult<int>();
        }

        public virtual T Save(T t)
        {
            return Save(t, false);
        }

        public virtual T Save(T t, bool delayFlush)
        {
            Session.Save(t);
            if (!delayFlush) Session.Flush();
            return t;
        }

        public virtual void Save(IEnumerable<T> entities)
        {
            foreach (var entity in entities)
            {
                Save(entity, false);
            }
            Session.Flush();
        }

        public virtual void Delete(T t)
        {
            Delete(t, false);
        }

        public virtual void Delete(T t, bool delayFlush)
        {
            Session.Delete(t);
            if (!delayFlush) Session.Flush();
        }

        public virtual void Flush()
        {
            Session.Flush();
        }


        public virtual T GetById(TId id)
        {
            return Session.Get<T>(id);
        }
    }
}